package websocket

import (
	"encoding/json"
	"net/url"

	"github.com/gorilla/websocket"
)

type Client interface {
	Close() error
	Send(v any) error
	SendUid(v any, uids ...string) error
	// Read(v any) error
}

type client struct {
	*websocket.Conn
	host string
	opt  dailOption
	Discover
}

func (c *client) Close() error {
	return c.Conn.Close()
}

func (c *client) Send(v any) error {
	data, err := json.Marshal(v)
	if err != nil {
		return err
	}
	err = c.Conn.WriteMessage(websocket.TextMessage, data)
	return nil
}

func (c *client) SendUid(v any, uids ...string) error {
	if c.Discover != nil {
		return c.Discover.Transpond(v, uids...)
	}
	return c.Send(v)
}

// func (c *client) Read(v any) error {
// 	return nil
// }

func NewClient(addr string, opts ...DailOptions) Client {
	opt := newClientOptions(opts...)

	url := url.URL{Scheme: opt.scheme, Host: addr, Path: opt.pattern}
	c, _, err := websocket.DefaultDialer.Dial(url.String(), nil)
	if err != nil {
		return nil
	}
	return &client{
		Conn: c,
		host: addr,
		opt:  opt,
	}
}
